package com.smart.car.message.controller;

import com.smart.car.common.res.bean.ResponseResult;
import com.smart.car.common.res.exception.BusinessException;
import com.smart.car.message.entity.MessageInfo;
import com.smart.car.message.service.MessageInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 消息控制
 * @author: zoutao.blog.csdn.net
 * @date: 2021-04-20
 */
@Slf4j
@RestController
@RequestMapping("message")
public class MessageController {

    @GetMapping("/test")
    public String test() {
        log.info("hello-江湖一点雨");
        return "hello-world-江湖一点雨";
    }

    @Autowired
    private MessageInfoService messageInfoService;

    /**
     *  查询历史消息记录
     */
    @GetMapping("/list")
    public List<MessageInfo> list() {
        List<MessageInfo> messages = messageInfoService.list();
        log.debug("查询历史消息记录： " + messages);
        return messages;
    }

    @Autowired
    private MessageInfoService messageService;

    /**
     * 记录发送过的消息通知
     */
    @PostMapping("/sendNotice")
    public ResponseResult<Integer> sendNotice(@RequestParam("json") String json) throws BusinessException {
        log.info("获取到的消息msg：" + json);
        ResponseResult<Integer> commonResult = new ResponseResult<>();
        int rtn = messageService.sendNotice(json);
        commonResult.setData(rtn);
        return commonResult;
    }



    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 腾讯云发送短信接口
     * @param phoneNum 手机号
     * @return String
     */
    @GetMapping("/sendSmsByTx")
    public String sendSmsByTx(@RequestParam("phoneNum") String phoneNum) throws Exception{
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String phone = opsForValue.get(phoneNum);
        // 如果手机号在redis中不存在的话才进行发送验证码操作
        if (StringUtils.isEmpty(phone)) {
            // 生成4位随机数
            String code  = String.valueOf(Math.random()).substring(3, 7);
            // 设置redis有效期
            long eTime = 5;
            // 调用业务层接口 发送验证码
            boolean sendSmsFlag = messageService.sendSmsByTx(phoneNum, code, eTime);
            if (sendSmsFlag) {
                // 发送成功之后往redis中存入该手机号以及验证码 并设置超时时间5分钟
                opsForValue.set(phoneNum, code, eTime, TimeUnit.MINUTES);
                return "发送验证码到：" + phoneNum + "成功! " + "Message:" + sendSmsFlag;
            }
            return "发送验证码失败，请检查接口配置信息。Message:" + sendSmsFlag;
        } else {
            return "该手机号：" + phoneNum + "的验证码还没过期，剩余：" + redisTemplate.getExpire(phoneNum) + "秒后可再次进行发送！";
        }
    }

}
